
import { _decorator, Component, Node, Collider, ITriggerEvent } from 'cc';
import { Constant } from '../framework/Constant';
import { GameManager } from '../framework/gameManager';
import { PoolManager } from '../framework/PoolManager';
const { ccclass, property } = _decorator;

const OUTOFBOUNCE=50;  //边界
@ccclass('EnemyPlane')
export class EnemyPlane extends Component {
    @property
    public createBulletTime=0.5; 
 
    private _enemySpeed=0;
    private _needBullet=false;
    //public enemyType=Constant.EnemyPlan.TYPE1;
    public _GameManager:GameManager=null;
    private  _currCreateBulletTime=0;

    onEnable () {
        const  collider=this.getComponent(Collider);
        collider.on('onTriggerEnter',this._onTriggerEnter,this);
    }

    onDisable () {
        const  collider=this.getComponent(Collider);
        collider.off('onTriggerEnter',this._onTriggerEnter,this);
    }

    update (deltaTime: number) 
    {
        const pos=this.node.position;
        const movepos=pos.z+this._enemySpeed;
        this.node.setPosition(pos.x,pos.y,movepos);

        if(this._needBullet)
        {
            this._currCreateBulletTime+=deltaTime;
            if(this._currCreateBulletTime>this.createBulletTime)
            {
                this._GameManager.createEnemyBullet(this.node.position);
                this._currCreateBulletTime=0;
            }
        }
        if(movepos>OUTOFBOUNCE)
        {
            PoolManager.instance().putNode(this.node);
            //this.node.destroy();
        }
    }
    show(gameManager:GameManager,speed:number,needBullet:boolean)
    {
        this._GameManager=gameManager;
        this._enemySpeed=speed;
        this._needBullet=needBullet;
    }

    private _onTriggerEnter(event:ITriggerEvent)
    {
       const collisionGroup=event.otherCollider.getGroup();
       if(collisionGroup===Constant.CollisionType.SELE_BULLET||collisionGroup===Constant.CollisionType.SELF_PLAN)
       {
           console.log('trigger enemy destory');
           this._GameManager.playerAudioEffect('enemy');
           //this.node.destroy();
           this._GameManager.addScore();
           PoolManager.instance().putNode(this.node);
           this._GameManager.createBulletEffect(this.node.position);
       }
    }

}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.0/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.0/manual/en/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.0/manual/en/scripting/life-cycle-callbacks.html
 */
